package cn.yunhe.servlet;

import cn.yunhe.bean.Emp;
import cn.yunhe.dao.IEmpDao;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/mavenServlet")
public class MavenServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        PrintWriter out = resp.getWriter();
        //读取mybatis的配置文件
        InputStream inputStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        //创建factory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
        //创建SqlSession对象
        SqlSession sqlSession = factory.openSession();
        IEmpDao empDao = sqlSession.getMapper(IEmpDao.class);
        //执行功能
        List<Emp> empList = empDao.queryEmps();
        //关闭sqlSession对象
        sqlSession.close();

        //将Java对象转换为json字符串
        out.write(JSON.toJSONString(empList));
        out.close();
    }
}
